-module(element_register).
-include_lib("nitrogen/include/wf.inc").
-compile(export_all).

render() ->
    Body = [
	    #p{},
	    #label{ text="Nom d'utilisateur : " },
	    #textbox{ id=nick },

	    #p{},
	    #label{ text="Mot de passe : " },
	    #password{ id=pass },

	    #p{},
	    #label{ text="Confirmez : " },
	    #password{ id=confirm },

	    #p{},
	    #label{ text="Email : " },
	    #textbox{ id=email },

	    #p{},
	    #button{ id=register, text="S'enregistrer !", actions=helper:act(?MODULE, register) }
	   ],

    wf:wire(register, nick, #validate {
			validators=[
				    #is_required { text = "X" }
				   ] }),
    wf:wire(register, pass, #validate {
			validators=[
				    #is_required { text="X" },
				    #min_length { length=5, text=">5" }
				   ] }),
    wf:wire(register, confirm, #validate {
			validators=[
				    #is_required { text="X" },
				    #confirm_password { password=pass,  text="X" }
				   ] }),
    wf:wire(register, email, #validate { 
			validators=[
				    #is_required { text="X" },
				    #is_email { text="X" }
				   ]}),
    wf:render(Body).

event(register) ->
    [Nick] = wf:q(nick),
    [Pass] = wf:q(pass),
    [Email] = wf:q(email),
    case db:add(member, {Nick, Pass, Email}) of
	{ok, _} -> wf:redirect("/web/index");
	{error, bad_nick} -> wf:flash("Votre nom d'utilisateur est déjà utilisé, veuillez en choisir un nouveau");
	{error, Reason} -> wf:flash("Erreur : " ++ Reason);
	_ -> wf:flash("Erreur inconnue")
    end;
event(_) -> ok.
